package com.example.yunJie.digitalSentry.component;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.yunJie.digitalSentry.mapper.one", sqlSessionFactoryRef = "OneSqlSessionFactory")
public class OneDateSourceConfig {

        @Bean(name = "OneDataSource")
        @Primary
        @ConfigurationProperties(prefix = "spring.datasource.one")
        public DataSource getDateSource1() {
            return DataSourceBuilder.create().build();
        }


        @Bean(name = "OneSqlSessionFactory")
        @Primary
        public SqlSessionFactory test1SqlSessionFactory(
                @Qualifier("OneDataSource") DataSource datasource) throws Exception {
            MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean ();
            bean.setDataSource(datasource);
            bean.setMapperLocations(// 设置mybatis的xml所在位置
                    new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/one/*.xml"));
            return bean.getObject();
        }


        @Bean("OneSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate test1SqlSessionTemplate(
                @Qualifier("OneSqlSessionFactory") SqlSessionFactory sessionFactory) {
            return new SqlSessionTemplate(sessionFactory);
        }

        @Bean
        public PlatformTransactionManager oneTransactionManager(@Qualifier("OneDataSource")DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }




}
